;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.SafeAndLack", [])
        .controller("SafeAndLackCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE","$filter","$timeout", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService) {
            $scope.activeFlag = [true, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                curRow: 0
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.dataList = [];
            $scope.dataObj = {};
            $scope.condition = {};
            $scope.btnEnabled = true;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.exportParam = {
				sectionUrl: ybHttp.RequestUrl("device", "/safetyStockAndLack/export"),
				sectionParam: { ids: [] },
				allUrl: ybHttp.RequestUrl("device", "/safetyStockAndLack/exportAll")
            };
            $scope.tableConfig = {
                fixedWidth: 120,
                scrollWidth: 1500,
                tableCol: [
                    {
                        type: "",
                        name: "零件编号",
                        dataField: "materialsNo",
                        width: 150,
                        isShow: true,
                        isFixed: true,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "零件中文名",
                        dataField: "materialsDes",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },

                    {
                        type: "safetyStock",
                        name: "安全库存",
                        dataField: "safetyStock",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "库存现有量",
                        dataField: "inStock",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "缺货数量",
                        dataField: "lackNum",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 220,
                        isShow: true,
                        isFixed: true,
                    }
                ]
            };

            function initData() {
                $scope.dataObj = {};
            }

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false];
                $scope.activeFlag[index] = true;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    default:
                        break;
                }
            };

            var btnPermissionCode = {
                safeAndLackAdd: window.ActionCode.safeAndLackAdd,
                safeAndLackImport: window.ActionCode.safeAndLackImport
            };

            $scope.btnPermission = {
                safeAndLackAdd: true,
                safeAndLackImport: true,
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            function getDataList(curPage) {
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/safetyStockAndLack/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.updateTimeShow = $filter("YbDate")(item.updateTime,"yyyy-MM-dd HH:mm:ss");
                        if(!item.adjustSafetyStock){
                            item.adjustSafetyStock = item.calSafetyStock;
                        }
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;

                });
            }

            function geBillIds() {
				$scope.exportParam.sectionParam.ids = [];
				angular.forEach($scope.dataList, function (item) {
					if (!!item.isChecked) {
						$scope.exportParam.sectionParam.ids.push(item.id);
					}
				});
			}
			function checkAll() {
				var selectAll = false;
				for (var i = 0, len = $scope.dataList.length; i < len; i++) {
					if (!$scope.dataList[i].isChecked) {
						selectAll = false;
						break;
					}
					selectAll = true;
				}
				return selectAll;
			}

			$scope.selectSingle = function (item) {
				if (!item.isChecked) {
					$scope.markInfo.allChecked = false;
				} else {
					if (!checkAll()) {
						$scope.markInfo.allChecked = false;
					} else {
						$scope.markInfo.allChecked = true;
					}
				}
				geBillIds();
			};

			$scope.selectAll = function () {
				for (var i = 0, len = $scope.dataList.length; i < len; i++) {
					$scope.dataList[i].isChecked = $scope.markInfo.allChecked;
				}
				geBillIds();
			};


            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(1, item);
                        break;
                    default:
                        break;
                }
            };

            $scope.searchDetail = function () {
                viewDetail();
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            $scope.selectScheme = function() {
                $scope.btnEnabled = false;
            };

            $scope.addData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/safetyStockAndLack/save";
                if ( $scope.dataObj.id) {
                    reqUrl = "/safetyStockAndLack/update"
                }
                ybHttp.Post(service, reqUrl, $scope.dataObj).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0)
                    $scope.btnEnabled = false;

                });
            };

            $scope.saveData = function () {
                var service = "device";
                var reqUrl = "/safetyStockAndLack/update";
                ybHttp.Post(service, reqUrl, $scope.dataList).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.btnEnabled = false;
                });
            };

            $scope.importSafeInventory = function () {
                var param = {
                    name: "安全库存",
                    templateReqService: "device",
                    templateReqUrl: "/safetyStockAndLack/download",
                    importReqService: "device",
                    importReqUrl: "/safetyStockAndLack/importSafetyStock",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);